using System.Linq;
using Illinois.Core.Interfaces;
using Illinois.Core.Models;

namespace Illinois.Core.Services
{
  public class UserService : IUserService
  {
    private readonly IUserRepository _repository;

    public UserService(IUserRepository repository)
    {
      _repository = repository;
    }

    public User GetUser(string username, string password)
    {
      var user = _repository.Find(e => e.UserName == username && e.Password == GetMd5Hash(password));
      return user.Any() ? user.First() : null; // todo: use nullobject pattern
    }

    // see: [assembly: InternalsVisibleTo("Illinois.Core.Test")]
    internal static string GetMd5Hash(string input)
    {
      var provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
      var buffer = System.Text.Encoding.UTF8.GetBytes(input);
      buffer = provider.ComputeHash(buffer);
      var builder = new System.Text.StringBuilder();
      foreach (var item in buffer)
      {
        builder.Append(item.ToString("x2").ToLower());
      }
      var hash = builder.ToString();
      return hash;
    }
  }
}
